<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="geometry" content="facet">
  <link rel="stylesheet" href="./assets/common.css">
  <title>Facets Mirror</title>
</head>

<body>
  <div>
    <label for="">选择年份</label>
    <select name="" id="selYear"></select>
  </div>
  <div id="canvas"></div>
  <script src="./assets/jquery-3.2.1.min.js"></script>
  <script src="../build/g2.js"></script>
  <script src="./assets/data-set.min.js"></script>
  
  <script>
    $.getJSON('./data/population.json', data => {
      const tmp = [];
      const dates = [];
      const selEl = $('#selYear');
      data.male.values.forEach(function(obj) {
    
        if (dates.indexOf(obj.date) === -1) {
          dates.push(obj.date);
        }
        obj.age_groups.forEach(function(subObject) {
          subObject.gender = 'male';
          subObject.date = obj.date;
          tmp.push(subObject);
        });
    
      });
      data.female.values.forEach(function(obj) {
        obj.age_groups.forEach(function(subObject) {
          subObject.gender = 'female';
          subObject.date = obj.date;
          tmp.push(subObject);
        });
      });
      dates.forEach(date => {
        $('<option value="' + date + '">' + new Date(date * 1000).getFullYear() + '</option>').appendTo(selEl);
      });
      const ds = new DataSet({
        state: {
          date: dates[0]
        }
      });

      const dv = ds.createView()
                  .source(tmp)
                  .transform({
                    type: 'filter',
                    callback(row) { // 判断某一行是否保留，默认返回true
                      return new Date(row.date * 1000).getFullYear() === new Date(ds.state.date * 1000).getFullYear();
                    }
                  });

      const chart = new G2.Chart({
        container: 'canvas',
        forceFit: true,
        height: window.innerHeight
      });

      chart.source(dv, {
        age: {
          sync: true,
          tickCount: 11
        },
        total_percentage: {
          sync: true,
          formatter(v) {
            return v + '%';
          }
        },
        gender: {
          sync: true
        }
      });
      chart.facet('mirror', {
        fields: [ 'gender' ],
        eachView(view) {
          view.interval().position('age*total_percentage')
            .color('gender', [ 'rgb(113,192,235)', 'rgb(246,170,203)' ]);
        }
      });
      chart.render();

      selEl.on('change', function() {
        const val = selEl.val();
        const date = parseInt(val);
        ds.setState('date', date);
      });
    });
  </script>
</body>
</html>